class LoginController < ApplicationController
  layout "login"
  # The login index action
  before_filter :authorize, :except => [:index, :signup, :logout]
  
  def index
    # The page title. This will be replaced with configurations in
    # system admin module. Now just hard-code it.
    # The following line is used to prevent logged-in user re-login.
    redirect_to(:controller => :home, :action => :index) \
      unless session[:user_name].nil?
    
    @page_title = "Login to Microblog"
    if request.post?
      @user = User.authenticate(params[:name], params[:password])
      if @user
        session[:user_name] = @user.name
        redirect_to(:controller => :home, :action => :index)
      else
        flash[:notice] = "User name or password wrong!"
      end
    end
  end
  
  # The signup action
  def signup
    # The following line is used to prevent logged-in user re-signup.
    redirect_to(:controller => :home, :action => :index) unless session[:user_name].nil?
    
    @page_title = "Sign Up for Microblog"
    @user = User.new(params[:user])
    begin
      if request.post? and @user.save
        flash[:notice] = \
          "Your account: \"#{@user.name}\" has been successfully created!"
        @user = User.new
        # After user creation, goto login page.
        redirect_to(:controller => :login)
      end
    rescue Exception => e
      p e.message
    end
  end
  
  def logout
    if session[:user_name]
        session[:user_name]= nil
        flash[:notice] = "You've been successfully logged out!"
    end
    redirect_to(:controller => :home, :action => :index)
  end

end
